﻿using System;
using System.Net;
using Fetches.Fetch.Dto;
using Newtonsoft.Json;

namespace Fetches.Fetch.Proxy
{
    internal class ResultMessage
    {
        public int Code { get; set; }
        public string Msg { get; set; }
        public string Data { get; set; }
    }

    public class DemoProxyPool:IProxyPool
    {
        private string _providerUrl;
        private WebClient _client;
        public void Initialize(string config, long uniqueId)
        {
            _providerUrl = config;
            _client=new WebClient();
        }

        public Proxy GetValidProxy(string testUrl, int timeout)
        {
            return GetProxyByUrl(_providerUrl + "&mode=random");
        }

        public void Return(Proxy proxy)
        {
            _client.UploadString(_providerUrl, proxy.UniqueName);
        }

        public void ReportProxyUsage(Proxy proxy, Request request, HttpStatusCode statusCode)
        {
            throw new NotImplementedException();
        }

        private Proxy GetProxyByUrl(string url)
        {
            try
            {
                var result = JsonConvert.DeserializeObject<ResultMessage>(_client.DownloadString(url));
                if (result.Code != 0)
                {
                    throw new Exception("获取失败");
                }
                return JsonConvert.DeserializeObject<Proxy>(result.Data);
            }
            catch (Exception)
            {
                return null;
            }

        }
    }
}
